package com.suredy.app.porject.service;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.suredy.app.porject.constants.ContractType;
import com.suredy.app.porject.model.Contract;
import com.suredy.app.porject.model.ContractMoney;
import com.suredy.core.service.BaseSrvWithEntity;

@Service
public class ContractMoneySrv extends BaseSrvWithEntity<ContractMoney> {

	public ContractMoneySrv() {
		this.addAnDefOrder("time", true);
		this.addAnDefOrder("name", true);
	}

	@Override
	public DetachedCriteria getDc(ContractMoney t) {
		DetachedCriteria dc = super.getDc(t);

		if (t == null)
			return dc;

		if (!StringUtils.isBlank(t.getId())) {
			dc.add(Restrictions.eq("id", t.getId()));
		}
		if (t.getPayOut() != null) {
			dc.add(Restrictions.eq("payOut", t.getPayOut()));
		}
		if (!StringUtils.isBlank(t.getName())) {
			dc.add(Restrictions.eq("name", t.getName()));
		}
		if (!StringUtils.isBlank(t.getSource())) {
			dc.add(Restrictions.like("source", t.getSource(), MatchMode.ANYWHERE));
		}

		return dc;
	}

	public boolean asBusinessMoney(String id) {
		if (StringUtils.isBlank(id))
			return false;

		String ql = "SELECT T, T.contract.id, T.contract.type FROM ContractMoney T WHERE T.id = ?";

		Object[] data = (Object[]) this.readSingleByQL(ql, id);

		if (data == null || data.length != 3)
			return false;

		ContractMoney cm = (ContractMoney) data[0];
		String cId = (String) data[1];
		ContractType cType = (ContractType) data[2];

		ContractMoney m = new ContractMoney();

		m.setContract(new Contract());
		m.getContract().setId(cId);
		m.setPayOut(!cType.isCollection());
		m.setInAccount(true);
		m.setSource(cm.getSource());
		m.setTime(cm.getBackTime());
		m.setTotal(cm.getTotal());
		m.setInvoice(true);
		m.setInvoiceTotal(cm.getTotal());
		m.setRemark(cm.getName() + "转" + (cType.isCollection() ? "收" : "付") + "款");

		m = this.save(m);

		if (m == null || StringUtils.isBlank(m.getId()))
			return false;

		return true;
	}
}
